package cn.com.b2office.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.com.b2office.dao.AddressDao;
import cn.com.b2office.domain.AccountActivity;
import cn.com.b2office.domain.City;
import cn.com.b2office.domain.County;
import cn.com.b2office.domain.District;
import cn.com.b2office.domain.ExData;
import cn.com.b2office.domain.MemberAddress;
import cn.com.b2office.exchange.ClassMapping;

/**
 * @author zhenggang
 * @version Jul 18, 2008 1:56:08 PM comment
 */
public class AddressDaoHibernateImpl extends HibernateDaoSupport implements
		AddressDao {

	public static final String LIST_CITIES = "from City";

	public static final String LIST_DISTRICT_BY_CITY_ID = "from District where cityid = :cityId";

	public static final String LIST_COUNTIES_BY_DISTRICT_ID = "from County where district = :districtId";

	public static final String GET_ADDRESSINFO_BY_MEMBER_ID = "from MemberAddress where memberid=?";

	@SuppressWarnings("unchecked")
	public List<City> listCities() {
		List<City> list = null;
		Session s = getSession();
		try {
			Query query = s.createQuery(LIST_CITIES);
			query.setCacheable(true);
			list = query.list();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<District> listDistrictsByCityId(int cityId) {

		List<District> list = null;
		Session s = getSession();
		try {
			Query query = s.createQuery(LIST_DISTRICT_BY_CITY_ID).setInteger(
					"cityId", cityId);
			query.setCacheable(true);
			list = query.list();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<County> listCountiesByDistrictId(int districtId) {

		List<County> list = null;
		Session s = getSession();
		try {
			Query query = s.createQuery(LIST_COUNTIES_BY_DISTRICT_ID)
					.setInteger("districtId", districtId);
			query.setCacheable(true);
			list = query.list();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	public MemberAddress getAddressInfoByMemberId(String memberId) {
		List list = getHibernateTemplate().find(GET_ADDRESSINFO_BY_MEMBER_ID,
				memberId);
		if (list.size() == 0) {
			return null;
		} else {
			return (MemberAddress) list.get(0);
		}

	}

	public List<District> listDistricts() {
		List<District> list = null;
		Session s = getSession();
		try {
			Query query = s.createQuery("from District");
			query.setCacheable(true);
			list = query.list();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}
}
